package com.rbac.application.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.application.service.OperationLogService;
import com.rbac.domain.dto.query.OperationLogPageQuery;
import com.rbac.domain.entity.OperationLog;
import com.rbac.infrastructure.mapper.OperationLogMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@RequiredArgsConstructor
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public IPage<OperationLog> pageOperationLogs(OperationLogPageQuery query) {
        Page<OperationLog> page = new Page<>(query.getPage(), query.getSize());
        LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
        
        wrapper.like(StrUtil.isNotBlank(query.getUsername()), OperationLog::getUsername, query.getUsername())
                .like(StrUtil.isNotBlank(query.getOperation()), OperationLog::getOperation, query.getOperation())
                .like(StrUtil.isNotBlank(query.getMethod()), OperationLog::getMethod, query.getMethod())
                .like(StrUtil.isNotBlank(query.getIp()), OperationLog::getIp, query.getIp())
                .eq(query.getStatus() != null, OperationLog::getStatus, query.getStatus());

        if (StrUtil.isNotBlank(query.getStartTime())) {
            wrapper.ge(OperationLog::getCreatedTime, LocalDateTime.parse(query.getStartTime() + " 00:00:00", formatter));
        }
        if (StrUtil.isNotBlank(query.getEndTime())) {
            wrapper.le(OperationLog::getCreatedTime, LocalDateTime.parse(query.getEndTime() + " 23:59:59", formatter));
        }

        wrapper.orderByDesc(OperationLog::getCreatedTime);
        return this.page(page, wrapper);
    }

    @Override
    public OperationLog getLogById(Long id) {
        return this.getById(id);
    }

    @Override
    public void saveLog(OperationLog log) {
        log.setCreatedTime(LocalDateTime.now());
        this.save(log);
    }

    @Override
    public List<OperationLog> getLogsByUserId(Long userId) {
        return baseMapper.getLogsByUserId(userId);
    }

    @Override
    public void cleanOldLogs(int days) {
        LocalDateTime beforeDate = LocalDateTime.now().minusDays(days);
        baseMapper.deleteOldLogs(beforeDate);
    }

    @Override
    public void exportLogs(OperationLogPageQuery query) {
        // TODO: 实现日志导出功能
        // 可以使用 EasyExcel 或 Apache POI 导出到 Excel
        // 或者生成 CSV 文件
    }
}